package com.lzx.applib.utils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    static MessageDigest MD5 = null;

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
            ne.printStackTrace();
        }
    }

    public static String getMD5(File file) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
			byte[] buffer = new byte[8192];
			int length;
			while ((length = fileInputStream.read(buffer)) != -1) {
				MD5.update(buffer, 0, length);
			}
			return getHexString(MD5.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			StreamUtil.closeSafely(fileInputStream);
		}
	}

	public static String getMd5(String plainText) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(plainText.getBytes());
		return  getHexString(md.digest());
	}

    static String getHexString(byte[] data) {
        StringBuilder result = new StringBuilder();
        for (byte b : data) {
            String temp1 = Integer.toHexString(b>>4&0xf);
            String temp2 = Integer.toHexString(b&0xf);
            result.append(temp1).append(temp2);
        }
        return result.toString().toUpperCase();
    }
}
